package com.heitian.ssm.service.impl;

import com.heitian.ssm.dao.AttachDao;
import com.heitian.ssm.model.Attach;
import com.heitian.ssm.model.PageBean;
import com.heitian.ssm.model.User;
import com.heitian.ssm.service.AttachService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 作者： 陈建峰
 * 创建时间： 18/3/27 下午10:26
 * 版本： [1.0, 18/3/27]
 * 描述： 文件处理
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AttachServiceImpl implements AttachService{

    @Resource
    private AttachDao attachDao;

    /**
     * 保存文件
     * @param attach
     */
    public void SaveAttach(Attach attach) {
        attachDao.saveAttach(attach.AttachGuid,attach.AttachName,attach.AttachLength,attach.AttachUrl,attach.UpdataTime,
                attach.OwnerUserGuid,attach.AlbumGuid,attach.AttachType,attach.CategoryType,attach.AttachState);
    }

    /**
     * 删除文件
     * @param attachGuid
     */
    public void DeleteAttach(String attachGuid) {
        attachDao.deleteAttach(attachGuid);
    }

    /**
     * 获取相册下的附件数量
     * @param albumGuid
     * @return
     */
    public int getAllAttachCountByAlbumGuid(String albumGuid) {
        return attachDao.getAllAttachCountByAlbumGuid(albumGuid);
    }

    /**
     * 获取附件
     * @param attachGuid
     * @return
     */
    public Attach getAttachByGuid(String attachGuid) {
        return attachDao.getAttachByGuid(attachGuid);
    }

    /**
     * 获取文件列表
     * @param albumGuid
     * @param index
     * @param currentPageCount
     * @return
     */
    public PageBean<Attach> getAttachByAlbumGuid(String albumGuid, int index, int currentPageCount) {
        //封装一个PageBean 返回web层
        PageBean<Attach> pageBean = new PageBean<Attach>();
        //1、封装当前页
        pageBean.setCurrentPage(index);
        //2、封装每页显示的条数
        pageBean.setCurrentCount(currentPageCount);
        //3、封装总条数
        int totalCount = attachDao.getAllAttachCountByAlbumGuid(albumGuid);
        pageBean.setTotalCount(totalCount);
        //4、封装总页数
        int totalPage = (int) Math.ceil(1.0*totalCount/currentPageCount);
        pageBean.setTotalPage(totalPage);
        //5、当前页显示的数据
        // select * from product where cid=? limit ?,?
        // 当前页与起始索引index的关系
        int indexes = (index-1)*currentPageCount;
        List<Attach> list = attachDao.getAllAttachByAlbumGuid(albumGuid,indexes,currentPageCount);
        pageBean.setList(list);
        return pageBean;
    }

    /**
     * 获取文件所有数量
     * @return
     */
    public int getAllAttachCount() {
        return attachDao.getAllAttachCount();
    }
}
